package com.wqj.kyee.mmitest

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import org.jetbrains.anko.setContentView
import android.app.PendingIntent
import android.content.IntentFilter
import android.content.IntentFilter.MalformedMimeTypeException
import android.nfc.*
import android.nfc.tech.NfcA
import android.nfc.tech.NfcB
import android.nfc.tech.NfcF
import android.nfc.tech.NfcV
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import org.jetbrains.anko.find
import android.nfc.tech.Ndef
import java.io.IOException
import java.nio.charset.Charset
import android.nfc.NdefRecord
import java.io.UnsupportedEncodingException


class NfcActivity : AppCompatActivity() {



    lateinit private var techListsArray: Array<Array<String>>

    lateinit private var intentFiltersArray: Array<IntentFilter>

    lateinit private var pendingIntent: PendingIntent

    lateinit private var mAdapter: NfcAdapter
    lateinit private var rst_text: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        NfcUi().setContentView(this@NfcActivity)
        rst_text = this.find<TextView>(NfcUi.ID_RST_TEXT)
        pendingIntent = PendingIntent.getActivity(
                this, 0, Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)
        val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
        try {
            ndef.addDataType("*/*")    /* Handles all MIME based dispatches.
                                       You should specify only the ones that you need. */
        } catch (e: MalformedMimeTypeException) {
            throw RuntimeException("fail", e)
        }
        intentFiltersArray = arrayOf(ndef)
        techListsArray = arrayOf(arrayOf(NfcF::class.java.name, NfcA::class.java.name
                , NfcB::class.java.name, NfcV::class.java.name))

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    override fun onPause() {
        super.onPause()
        mAdapter.disableForegroundDispatch(this);
        Log.d("wqj", "on Pause ")
    }

    override fun onResume() {
        super.onResume()
        mAdapter.enableForegroundDispatch(this, pendingIntent, /*intentFiltersArray*/null, /*techListsArray*/ null);
        Log.d("wqj", "on Resume ")
    }

    lateinit var tag: Tag

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        Log.d("wqj", "tag: ")
        val action = intent?.getAction()
        rst_text.append("\n卡类型: ")
        when (action) {
            NfcAdapter.ACTION_NDEF_DISCOVERED -> {

                rst_text.append("NDEF")
            }
            NfcAdapter.ACTION_TECH_DISCOVERED -> {

                rst_text.append("TECH")
            }
            NfcAdapter.ACTION_TAG_DISCOVERED -> {

                rst_text.append("TAG")
            }
            else -> {
                return
            }
        }
        tag = intent?.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        var id = tag.getId();
        rst_text.append("\n标签UID： " + ByteArrayToHexString(id))
        val techList = tag.getTechList();
        rst_text.append("\ntype: ")
        for ( str in techList) {

            rst_text.append(str + ", ")
        }
        rst_text.append("\n==========================================")
    }

    private fun read(tag: Tag?): String? {
        if (tag != null) {
            //解析Tag获取到NDEF实例
            val ndef = Ndef.get(tag)
            //打开连接
            ndef.connect()
            //获取NDEF消息
            val message = ndef.ndefMessage
            //将消息转换成字节数组
            val data = message.toByteArray()
            //将字节数组转换成字符串
            val str = String(data, Charset.forName("UTF-8"))
            //关闭连接
            ndef.close()
            return str
        } else {
            Toast.makeText(this@NfcActivity, "设备与nfc卡连接断开，请重新连接...",
                    Toast.LENGTH_SHORT).show()
        }
        return null
    }

    private fun write(tag: Tag) {
        if (tag != null) {
            //新建NdefRecord数组，本例中数组只有一个元素
            var records = createRecord()
            //新建一个NdefMessage实例
            var message = NdefMessage(records);
            // 解析TAG获取到NDEF实例
            var ndef = Ndef.get(tag);
            // 打开连接
            ndef.connect();
            // 写入NDEF信息
            ndef.writeNdefMessage(message);
            // 关闭连接
            ndef.close();
            rst_text.append("写入数据成功！" + "\n");
        } else {
            Toast.makeText(this@NfcActivity, "设备与nfc卡连接断开，请重新连接...",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private fun createRecord(): NdefRecord {
        //组装字符串，准备好你要写入的信息
        val msg = ("BEGIN:VCARD\n" + "VERSION:2.1\n" + "上海闵行\n"
                + "京颐股份\n" + "END:VCARD")
        //将字符串转换成字节数组
        val textBytes = msg.toByteArray()
        //将字节数组封装到一个NdefRecord实例中去
        return NdefRecord(NdefRecord.TNF_MIME_MEDIA,
                "text/x-vCard".toByteArray(), byteArrayOf(), textBytes)
    }

    fun ByteArrayToHexString(bytes: ByteArray): String {   //Byte数组转换为16进制字符串
        var i: Int
        var j: Int
        var tmp: Int
        var input: Int
        val hex = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var output = ""

        j = 0
        while (j < bytes.size) {
            tmp = bytes[j].toInt()
            input = tmp and 0xff
            i = input shr 4 and 0x0f
            output += hex[i]
            i = input and 0x0f
            output += hex[i]
            ++j
        }
        return output
    }
}
